package com.filefilter.util;


import com.filefilter.file.FilterListener;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.concurrent.TimeUnit;

/**
 * \* Created with IntelliJ IDEA.
 * \* Author: fly
 * \* Date: 2020/6/14
 * \* Time: 20:37
 * \* Description: 添加获取指定目录指定文件观察者的工具类
 * \
 */
@Component
public class FileMonitorUtils {
    @Resource
    private FilterListener filterListener;

    public FileAlterationMonitor getMonitor(File directory,Long intervalSeconds,String prefix,String suffix){
        //创建过滤器
        long interval = TimeUnit.SECONDS.toMillis(intervalSeconds);
        IOFileFilter directorys = FileFilterUtils.and(FileFilterUtils.directoryFileFilter());
        IOFileFilter suffixFilter = FileFilterUtils.suffixFileFilter(suffix);
//        IOFileFilter prefixFilter = FileFilterUtils.prefixFileFilter(prefix);
        IOFileFilter files = FileFilterUtils.and(FileFilterUtils.fileFileFilter(), suffixFilter);
        IOFileFilter filter = FileFilterUtils.or(directorys, files);
        //  装配过滤器

        FileAlterationObserver observer = new FileAlterationObserver(directory, filter);
        // 向监听者添加监听器，并注入业务
        observer.addListener(filterListener);
        FileAlterationMonitor monitor = new FileAlterationMonitor(interval,observer);
        return monitor;
    }
}

